package com.kaibes.module.file.local.api;

import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.kaibes.core.base.annotation.Description;
import com.kaibes.module.file.local.FileLocalService;
import com.kaibes.module.file.local.MD5String;
import com.kaibes.module.file.local.db.FileInfo;
import com.kaibes.module.file.local.db.FileInfoService;
import com.kaibes.module.file.local.db.FileMark;
import com.kaibes.module.file.local.db.FileMarkService;
import com.kaibes.module.file.local.to.PreloadTO;
import com.kaibes.module.file.local.to.UploadTO;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/files")
public class FileLocalApi {

    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private FileMarkService fileMarkService;
    @Autowired
    private FileLocalService fileLocalService;

    @PostMapping("/upload")
    @ApiLink(value = "上传文件", validated = false)
    public ResponseEntity<UploadTO> upload(@RequestAttribute Integer userId,
    		@RequestParam(required = false) @Description("MD5") String md5,
            @RequestParam(name = "file") @Description("上传的文件") MultipartFile multipartFile) {
        return fileLocalService.upload(userId, multipartFile, md5);
    }

    @PostMapping("/upload/pre")
    @ApiLink(value = "文件预上传，如果文件已存在会返回文件信息，否则返回文件不存在的提示", validated = false)
    public ResponseEntity<PreloadTO> preUpload(@RequestAttribute Integer userId,  @RequestBody @Description("文件MD5") MD5String md5String) {
        PreloadTO resultTO = new PreloadTO();
        FileInfo fileInfo = fileInfoService.getByMD5(md5String.getMd5().toUpperCase());
        if (fileInfo != null) {
            resultTO.setFlag(true);
            resultTO.setMsg("文件已存在");

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            FileMark fileMark = new FileMark();
            fileMark.setFileInfoId(fileInfo.getId());
            fileMark.setUuid(uuid);
            fileMark.setName(fileInfo.getName());
            fileMark.setUserId(userId);
            fileMark.setSuffix(fileInfo.getSuffix());
            fileMark.setType(fileInfo.getType());
            fileMarkService.save(fileMark);

            UploadTO uploadTO = new UploadTO();
            uploadTO.setMsg("上传文件成功");
            uploadTO.setUuid(uuid);
            uploadTO.setData(fileInfo);

            resultTO.setData(uploadTO);
        } else {
            resultTO.setFlag(false);
            resultTO.setMsg("文件不存在");
        }
        return ResponseFactory.postSuccess(resultTO);
    }

    @GetMapping("/md5/{md5}")
    @ApiLink(value = "获取文件", validated = true)
    public void getByMd5(HttpServletRequest request, HttpServletResponse response,
            @PathVariable @Description("文件md5") String md5) {
    	if (md5.contains(".")) {
    		md5 = md5.split("\\.")[0];
        }
        fileLocalService.getByFileInfo(request, response, fileInfoService.getByMD5(md5));
    }

    @GetMapping("/{uuid}")
    @ApiLink(value = "获取文件", validated = false)
    public void getByUuid(HttpServletRequest request, HttpServletResponse response,
            @PathVariable @Description("文件UUID") String uuid) {
        if (uuid.contains(".")) {
            uuid = uuid.split("\\.")[0];
        }
        FileMark fileMark = fileMarkService.getByUuid(uuid);
        if (fileMark != null) {
            FileInfo fileInfo = fileInfoService.getById(fileMark.getFileInfoId());
            fileLocalService.getByFileInfo(request, response, fileInfo);
        }
    }
    
    @GetMapping("/md5/{md5}/{name}")
    @ApiLink(value = "获取文件", validated = false)
    public void getByMd5(HttpServletRequest request, HttpServletResponse response,
            @PathVariable @Description("文件MD5") String md5,
            @PathVariable @Description("压缩包里文件名或位置") String name) {
        if (md5.contains(".")) {
        	md5 = md5.split("\\.")[0];
        }
        FileInfo fileInfo = fileInfoService.getByMD5(md5);
        if (fileInfo != null) {
            fileLocalService.getByFileInfo4list(request, response, fileInfo, name);
        }
    }
    
    @GetMapping("/{uuid}/{name}")
    @ApiLink(value = "获取文件", validated = false)
    public void getByUuid(HttpServletRequest request, HttpServletResponse response,
            @PathVariable @Description("文件UUID") String uuid,
            @PathVariable @Description("压缩包里文件名或位置") String name) {
        if (uuid.contains(".")) {
            uuid = uuid.split("\\.")[0];
        }
        FileMark fileMark = fileMarkService.getByUuid(uuid);
        if (fileMark != null) {
            FileInfo fileInfo = fileInfoService.getById(fileMark.getFileInfoId());
            fileLocalService.getByFileInfo4list(request, response, fileInfo, name);
        }
    }
    
    @GetMapping("/list/{uuid}")
    @ApiLink(value = "获取压缩文件长度", validated = false)
    public ResponseEntity<Object> get(@PathVariable @Description("文件的UUID") String uuid) {
        if (uuid.contains(".")) {
            uuid = uuid.split("\\.")[0];
        }
        HashMap<String, Integer> map = fileLocalService.list(uuid);
        return ResponseFactory.getSuccess(map);
    }

}
